<template>
  <el-form
    ref="loginFormRef"
    :model="loginForm"
    status-icon
    :rules="formRules"
    label-width="120px"
    class="login-form"
  >
    <h1><span>用户登录</span></h1>
    <el-form-item label="用户名" prop="username">
      <el-input class="e-input" v-model="loginForm.username" type="text" autocomplete="off" :prefix-icon="User" />
    </el-form-item>
    <el-form-item label="密码" prop="password">
      <el-input
        class="e-input"
        v-model="loginForm.password"
        :type="isHide ? 'password' : 'text'"
        autocomplete="off"
        :prefix-icon="Lock"
      >
        <template #suffix>
          <el-icon id="hide-button" @click="isHide = !isHide">
            <Hide v-if="isHide"></Hide>
            <View v-else></View>
          </el-icon>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item>
      <el-button id="login-button" type="primary" @click="submitForm(loginFormRef)" :loading="isLoading">
        登录
      </el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import { reactive, ref } from "vue"
import { User, Lock, View, Hide } from "@element-plus/icons-vue"
import type { FormInstance } from "element-plus"
import { useLoginStore } from "@/store/loginStore"
import { ElMessage } from "element-plus"
import {useRouter} from "vue-router"

const router = useRouter()

const loginFormRef = ref()

const loginForm = reactive({
  username: "",
  password: ""
})

//隐藏密码
const isHide = ref<boolean>(true)

//按钮加载状态
const isLoading = ref<boolean>(false)

const loginStore = useLoginStore()

//提交表单
function submitForm(form: FormInstance) {
  form.validate((valid: boolean) => {
    if (valid) {
      isLoading.value = true
      setTimeout(async () => {
        try {
          await loginStore.requestLogin({ username: loginForm.username.trim(), password: loginForm.password })
          ElMessage.success("登录成功！正在跳转...")
          await new Promise((resolve) => {
            setTimeout(() => {
              resolve("")
            }, 1000)
          })
          router.push({name: "home"})
        } catch (error: any) {
          ElMessage.error(error.msg)
        } finally {
          isLoading.value = false
        }
      })
    } else {
      return false
    }
  })
}

//验证用户名是否合法
function validateUsername(rule: any, value: string, callback: any): void {
  if (value === "" || /^\s*$/.test(value)) {
    callback(new Error("请输入用户名"))
  } else if (/\S\s\S/.test(value)) {
    callback(new Error("用户名中间不能包含空格"))
  }
  callback()
}

//验证密码是否合法
function validatePassword(rule: any, value: string, callback: any): void {
  if (value === "" || /^\s*$/.test(value)) {
    callback(new Error("请输入密码"))
  } else if (value.includes(" ")) {
    callback(new Error("密码不能包含空格"))
  }
  callback()
}

//配置校验规则
const formRules = reactive({
  username: [{ validator: validateUsername, trigger: "blur" }],
  password: [{ validator: validatePassword, trigger: "blur" }]
})
</script>

<style lang="scss" scoped>
:deep(.el-form-item__label) {
  user-select: none;
}

.login-form {
  border: 1px solid rgba(205, 198, 198, 0.957);
  border-radius: 10px;
  padding-top: 30px;
  padding-left: 0;
  width: 450px;
  box-shadow: 0px 5px 10px #cccc;
  height: 180 px;
  vertical-align: middle;
  text-align: center;
  font-weight: bolder;

  span {
    user-select: none;
    position: relative;
    bottom: 10px;
    left: 35px;
  }
}

.e-input {
  width: 300px;
}

#login-button {
  user-select: none;
  width: 300px;
}

#hide-button {
  cursor: pointer;
}
</style>
